package io.geekidea.boot.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.geekidea.boot.framework.exception.BusinessException;
import io.geekidea.boot.framework.page.OrderByItem;
import io.geekidea.boot.framework.page.OrderMapping;
import io.geekidea.boot.framework.page.Paging;
import io.geekidea.boot.business.dto.HazardUnitEventDto;
import io.geekidea.boot.business.mongodb.document.HazardUnitEvent;
import io.geekidea.boot.business.mapper.HazardUnitEventMapper;
import io.geekidea.boot.business.query.HazardUnitEventQuery;
import io.geekidea.boot.business.service.HazardUnitEventService;
import io.geekidea.boot.business.vo.HazardUnitEventVo;
import io.geekidea.boot.util.PagingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

/**
 * 设备部件存在安全隐患事件关联关系 服务实现类
 *
 * @author mr.wei
 * @since 2024-04-10
 */
@Slf4j
@Service
public class HazardUnitEventServiceImpl extends ServiceImpl<HazardUnitEventMapper, HazardUnitEvent> implements HazardUnitEventService {

    @Autowired
    private HazardUnitEventMapper hazardUnitEventMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addHazardUnitEvent(HazardUnitEventDto dto) {
        HazardUnitEvent hazardUnitEvent = new HazardUnitEvent();
        BeanUtils.copyProperties(dto, hazardUnitEvent);
        return save(hazardUnitEvent);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateHazardUnitEvent(HazardUnitEventDto dto) {
        Long id = dto.getId();
        HazardUnitEvent hazardUnitEvent = getById(id);
        if (hazardUnitEvent == null) {
            throw new BusinessException("设备部件存在安全隐患事件关联关系不存在");
        }
        BeanUtils.copyProperties(dto, hazardUnitEvent);
        return updateById(hazardUnitEvent);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteHazardUnitEvent(Long id) {
        return removeById(id);
    }

    @Override
    public HazardUnitEventVo getHazardUnitEventById(Long id) {
        return hazardUnitEventMapper.getHazardUnitEventById(id);
    }

    @Override
    public Paging<HazardUnitEventVo> getHazardUnitEventPage(HazardUnitEventQuery query) {
        OrderMapping orderMapping = new OrderMapping();
        orderMapping.put("createTime", "create_time");
        PagingUtil.handlePage(query, orderMapping, OrderByItem.desc("id"));
        List<HazardUnitEventVo> list = hazardUnitEventMapper.getHazardUnitEventPage(query);
        Paging<HazardUnitEventVo> paging = new Paging<>(list);
        return paging;
    }

}
